// import Home from '../../view/Home.vue'

class HistoryRoute {
  constructor() {
    this.current = []
  }
  pushHistory = (str) => {
    this.current.push(str)
  }
  go(num) {
    console.log('num', num)
    if (num < 0) {
      let i = 0
      while (i > num) {
        this.current.pop()
        i--
        console.log(i)
      }
      console.log(this.current)
      let path = this.current[this.current.length - 1]
      path = path === undefined ? '/' : path
      location.hash = path
    }
  }
}

class Router {
  constructor(options) {
    this.mode = options.mode || 'hash'
    this.routes = options.routes || []
    this.routesMap = this.createMap(this.routes)
    this.history = new HistoryRoute()
    this.init()
  }
  init() {
    if (this.mode === 'hash') {
      if (!location.hash) {
        location.hash = '#/'
      }
      window.addEventListener('hashchange', () => {
        this.history.pushHistory(location.hash.slice(1))
      })
      window.addEventListener('load', () => {
        this.history.pushHistory(location.hash.slice(1))
      })
      // Vue.util.defineReactive()
    } else if (this.mode === 'history') {
      console.log('history')
    }
  }

  createMap(routes) {
    let obj = Object.create(null)
    routes.forEach(route => {
      obj[route.path] = route.component
    })
    return obj
  }
  push(options) {
    if (options.path) {
      if (this.mode === 'hash')
        location.hash = options.path
    }
  }
  go(num) {
    this.history.go(num)
  }
}
let vue = null
Router.install = function (Vue) {
  if (vue != null) return
  vue = Vue
  Vue.mixin({
    beforeCreate() {
      if (this.$options && this.$options.router) {
        this._root = this
        this._router = this.$options.router
        Vue.util.defineReactive(this, 'xxx', this._router.history)
      } else {
        this._root = this.$parent && this.$parent._root
        this._router = this.$parent && this.$parent._root._router
      }
      Object.defineProperty(this, '$router', {
        get() {
          return this._router
        }
      })
      Object.defineProperty(this, '$route', {
        get() {
          return this._router.history.current
        }
      })
    }
  })
  console.dir('Vue', Vue)
  Vue.component('router-view', {
    render(h) {
      console.log(this._self)
      const routesMap = this._self._router.routesMap
      // const path = this._router.history.current
      const path = this._self.$route
      const c = routesMap[path[path.length - 1]]
      console.log('routesMap', routesMap)
      console.log('path', path)
      console.log('routesMap[path]', c)
      return h(c)
    }
  })
}

export default Router